import styles from './index.module.scss';
import Icon from '@/components/Icons';
import NavBar from '@/components/NavBar';
import { useParams } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import {
  collectByIdAction,
  delArticleDetailsAction,
  followUserByIdAction,
  getArticleDetailsByIdAction,
  likeByIdAction,
  unFollowUserByIdAction,
} from '@/store/action/article';
import { useAppSelector } from '@/store/reducer';
import DOMPurify from 'dompurify';
import dayjs from 'dayjs';
import SkeletonScreen from '@/components/SkeletonScreen';

// 代码高亮
import hljs from 'highlight.js';
// 可以去项目下找到各种各样的主题风格
import 'highlight.js/styles/vs2015.css';
import classNames from 'classnames';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import {
  ClearCommentsAction,
  getCommentsByIdAction,
} from '@/store/action/comments';
import CommentFooter from './components/CommentFooter';
import { Popup, Toast } from 'antd-mobile';
import CommentReply from './components/CommentReply';

export default function Article() {
  const { id } = useParams<{ id: string }>();
  const dispatch = useDispatch();
  const { details } = useAppSelector((state) => state.article);

  // 获取关注用户状态
  const { is_followed } = details;

  const [showNav, setShowNav] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const authRef = useRef<HTMLDivElement>(null);

  const commentRef = useRef<HTMLDivElement>(null);

  const [commentCeil, setCommentCeil] = useState(false);

  // 获取评论列表
  // originComment取出原始评论数据;
  const {
    // 给它默认空 [] 修复进入文章详情页时,文章评论数据有可能还没有,会报错的问题
    comments: { results: commentList = [] },
    originComment,
  } = useAppSelector((state) => state.comments);

  useEffect(() => {
    dispatch(getArticleDetailsByIdAction(id));
  }, [id, dispatch]);

  useEffect(() => {
    if (!details.art_id) return;
    // 💥 不要转义content中的html字符串
    hljs.configure({
      // 忽略未经转义的 HTML 字符,
      ignoreUnescapedHTML: true,
    });

    // 优先高亮code，code是pre的子标签，有code标签，一定有pre标签
    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length) {
      codes.forEach((item) => {
        hljs.highlightElement(item as any);
      });

      return;
    }

    // 如果不存在code标签，高亮pre标签
    const preCodes = document.querySelectorAll('.dg-html pre');
    if (preCodes.length) {
      preCodes.forEach((item) => {
        hljs.highlightElement(item as any);
      });
      return;
    }
  }, [details.art_id]);

  // 滚动事件
  const scrollFn = () => {
    // console.log(123);
    // ?.可选链(表示后面属性存在就访问)
    // const top = authRef.current?.getBoundingClientRect().top;

    // !.非空断言(表示该字段不是空的)
    const top = authRef.current!.getBoundingClientRect().top;
    // console.log(top);
    if (top < 10) {
      setShowNav(true);
    } else {
      setShowNav(false);
    }

    //评论头部吸顶效果
    const commentTop = commentRef.current!.getBoundingClientRect().top - 46;
    // console.log(commentTop);

    if (commentTop <= 0) {
      setCommentCeil(true);
    } else {
      setCommentCeil(false);
    }
  };

  useEffect(() => {
    if (!details.art_id) return;
    // window.addEventListener('scroll', () => {
    //   console.log(document.documentElement.scrollTop);
    // });
    //  注册事件
    wrapRef.current?.addEventListener('scroll', scrollFn);
  }, [details.art_id]);

  useEffect(() => {
    // 先在卸载前保存DOM
    const wrapDOM = wrapRef.current!;

    return () => {
      if (!details.art_id) return;
      dispatch(delArticleDetailsAction());
      dispatch(ClearCommentsAction());

      // 销毁事件
      //wrapRef.current有警告(这个是ts检查出来的,意思是组件卸载的时候,有可能wrapRef.current不存在了)
      // eslint-disable-next-line react-hooks/exhaustive-deps
      // wrapRef.current?.removeEventListener('scroll', scrollFn);

      // 销毁事件,先在卸载前保存DOM
      wrapDOM.removeEventListener('scroll', scrollFn);
    };
  }, [dispatch, details.art_id]);

  // 获取文章评论
  useEffect(() => {
    dispatch(getCommentsByIdAction({ type: 'a', source: id }));
  }, [id, dispatch]);

  // 点击评论滚动到评论列表
  const onShowComment = () => {
    // wrapRef.current!.scrollTop = commentRef.current!.offsetTop - 46;
    // scrollTo()传入对象形式,可以用behavior属性,设置滚动平滑效果
    wrapRef.current!.scrollTo({
      top: commentRef.current!.offsetTop - 46,
      behavior: 'smooth',
    });
  };

  // 关注用户
  const handleFollow = async () => {
    // console.log(details.aut_id);
    if (is_followed) {
      // 取消关注
      await dispatch(unFollowUserByIdAction(details.aut_id));
      Toast.show({ content: '取消关注成功' });
    } else {
      // 关注用户
      await dispatch(followUserByIdAction(details.aut_id));
      Toast.show({ content: '关注成功' });
    }
    dispatch(getArticleDetailsByIdAction(id));
  };

  // 对文章点赞/取消点赞
  const handleLike = async () => {
    const is_like = details.attitude === -1;
    await dispatch(likeByIdAction(details.art_id, is_like));
    await dispatch(getArticleDetailsByIdAction(id));
    Toast.show({ content: is_like ? '点赞成功' : '取消点赞成功' });
  };

  // 文章收藏/取消收藏
  const handleCollect = async () => {
    const { is_collected } = details;

    await dispatch(collectByIdAction(details.art_id, is_collected));
    await dispatch(getArticleDetailsByIdAction(id));
    Toast.show({ content: !is_collected ? '收藏成功' : '取消收藏成功' });
  };

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {/* // 放在NavBar组件标签之间 */}
          {showNav && (
            <div className="nav-author">
              <img src={details.aut_photo} alt="" />
              <span className="name">{details.aut_name}</span>
              <span
                onClick={handleFollow}
                className={classNames(
                  'follow',
                  details.is_followed ? 'followed' : ''
                )}
              >
                {details.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>

        {!details.aut_id ? (
          <SkeletonScreen></SkeletonScreen>
        ) : (
          <div className="wrapper" ref={wrapRef}>
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{details.title}</h1>

                <div className="info">
                  {/* 处理时间格式 */}
                  <span>{dayjs(details.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{details.read_count} 阅读</span>
                  <span>{commentList.length} 评论</span>
                </div>

                <div className="author" ref={authRef}>
                  <img src={details.aut_photo} alt="" />
                  <span className="name">{details.aut_name}</span>
                  <span
                    onClick={handleFollow}
                    className={details.is_followed ? 'followed' : 'follow'}
                  >
                    {details.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                <div
                  className="content-html dg-html"
                  // dangerouslySetInnerHTML属性解析HTML,  安全防御DOMPurify.sanitize
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(details.content),
                  }}
                ></div>
                <div className="date">
                  {/* 使用相对时间插件 */}
                  发布文章时间：{dayjs().from(details.pubdate)}
                </div>
                {/* ------------评论开始区域 */}
                <div className="divider"></div>
                <div className="comment" ref={commentRef}>
                  {/* 评论总览信息 */}
                  <div
                    className={
                      commentCeil
                        ? 'commentCeiling comment-header'
                        : 'comment-header'
                    }
                  >
                    <span>全部评论（{commentList.length}）</span>
                    <span>{details.like_count} 点赞</span>
                  </div>
                  {/* 吸顶时显示的占位 */}
                  {commentCeil && <div className="placeholder"></div>}

                  {/* 评论列表 */}
                  {commentList.length === 0 ? (
                    <NoComment />
                  ) : (
                    commentList.map((item) => (
                      <CommentItem comment={item} key={item.com_id} />
                    ))
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
        <CommentFooter
          onShowComment={onShowComment}
          handleLike={handleLike}
          handleCollect={handleCollect}
        ></CommentFooter>
        <Popup visible={!!originComment.com_id} position="right" destroyOnClose>
          <CommentReply></CommentReply>
        </Popup>
      </div>
    </div>
  );
}
